<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/10 0010
 * Time: 15:33
 */

namespace Cohuna\Controllers;


use Cohuna\Models\CohunaPermissionResource;
use Cohuna\Paginator\PaginatorArray;

/**
 * 资源管理
 * @package Cohuna\Controllers
 */
class ResourceController extends ControllerBase
{

    /**
     * 资源列表
     */
    public function listAction()
    {
        $resources = CohunaPermissionResource::getPermissionResourceGroup();


        $this->view->setVar('List',$resources);
    }

    /**
     * 编辑或添加资源
     */
    public function editAction()
    {
        if($this->request->isPost()){
            $resource_id = intval($this->request->getPost('resource_id'));
            if($resource_id > 0){
                $resource = CohunaPermissionResource::findFirstByResourceId($resource_id);
            }else{
                $resource = new CohunaPermissionResource();
            }
            $resource->resource_name = trim($this->request->getPost('resource_name'));
            $resource->display_name = trim($this->request->getPost('display_name'));
            $resource->controller_name = trim($this->request->getPost('controller_name'));
            $resource->action_name = trim($this->request->getPost('action_name'));
            $resource->icon_class = trim($this->request->getPost('icon_class'));
            $resource->sort_index = intval(trim($this->request->getPost('sort_index')));
            $resource->is_show_menu = intval(trim($this->request->getPost('is_show_menu'))) == 1 ? 1 : 0;
            if($resource_id <= 0) {
                $exists = CohunaPermissionResource::count(array('controller_name=:controller_name: AND action_name=:action_name:', 'bind' => array('controller_name' => $resource->controller_name, 'action_name' => $resource->action_name)));
                if ($exists > 0) {
                    output_json(5001, '资源已存在');
                }
            }
            $result = $resource->save();
            if($result){
                output_json(0,'保存成功',array('resource_id'=>$resource->resource_id));
            }else{
                output_json(5002,$resource->getError()->getMessage());
            }
        }
        $resource_id = intval($this->request->getQuery('resource_id'));

        if($resource_id > 0){
            $resource = CohunaPermissionResource::findFirstByResourceId($resource_id);
        }else{
            $resource = new CohunaPermissionResource();
        }

        $this->view->setVar('Model',$resource);
    }

    public function delAction()
    {
        $resource_id = intval($this->request->getPost('resource_id'));
        $resource = CohunaPermissionResource::findFirstByResourceId($resource_id);
        if(empty($resource)){
            output_json(4004,'资源不存在');
        }elseif($resource->delete()){
            output_json(0,'删除成功');
        }else{
            output_json(4005,'删除失败');
        }
    }
}